<script setup lang="ts">
import { useTemplateRef, watch } from 'vue'

const props = withDefaults(
  defineProps<{
    playing: boolean
  }>(),
  {
    playing: false,
  },
)

const videoWrapRef = useTemplateRef<HTMLDivElement | null>('videoWrapRef')
const svgRef = useTemplateRef<SVGSVGElement | null>('svgRef')
const replay = async () => {
  if (!videoWrapRef.value) {
    return
  }

  const currentVideo = videoWrapRef.value.querySelector(
    '& > video:not(.hidden)',
  ) as HTMLVideoElement | null
  if (currentVideo) {
    await currentVideo.play().catch()
    if (svgRef.value) {
      svgRef.value.classList.add('hidden')
    }
  }
}
watch(
  () => props.playing,
  (playing: boolean) => {
    if (svgRef.value) {
      if (playing) {
        svgRef.value.classList.add('hidden')
      } else {
        svgRef.value.classList.remove('hidden')
      }
    }
  },
  { immediate: true },
)
</script>

<template>
  <div class="relative" ref="videoWrapRef">
    <slot />

    <div
      class="absolute rounded-md top-[4%] right-[5%] flex items-center gap-[0.25rem] px-[8px] py-[2px] bg-[rgb(0_0_0/50%)]"
    >
      <img
        class="w-[1.1875rem] aspect-square"
        src="@/views/product/reno14-pro/image/4/images-live-2-live-1.png.webp"
        alt=""
        loading="lazy"
      />
      <p class="text-base">实况</p>
    </div>

    <svg
      class="w-[2rem] aspect-square absolute bottom-[4%] right-[5%]"
      @click="replay"
      ref="svgRef"
    >
      <use href="#icon-replay" />
    </svg>
  </div>
</template>
